<?php

namespace App\Http\Controllers;

use App\Article;
use App\Data;

class CollecController extends Controller
{
    //收藏Api
    public function collect($type,$id){
        $userinfo = request()->user();
        $collect['user_id'] = $userinfo->id;
        $collect['type'] = $type;
        if($type <5 ){
            $data = Data::find($id);
            $iscollect = $data->data()->where($collect)->get()->toArray();
            if(!empty($iscollect)){
                $data->data()->where($collect)->delete();
                $data->update(['collecnum'=>$data->collecnum -1]);
                return response()->json(['message' => '取消收藏', 'status' => 0]);
            }
            $data->data()->create($collect);
            $data->update(['collecnum'=>$data->collecnum +1]);
        }else{
            //文章收藏
            $article = Article::find($id);
            $iscollect = $article->article()->where($collect)->get()->toArray();
            if(!empty($iscollect)){
                $article->article()->where($collect)->delete();
                $article->save(['collecnum'=>$article->collecnum - 1]);
                return response()->json(['message' => '取消收藏', 'status' => 0]);
            }
            $article->article()->create($collect);
            $article->save(['collectnum'=>$article->collectnum + 1]);
        }
        return response()->json(['message' => '收藏成功', 'status' => 1]);

//        }else{
//            return response()->json(['message' => '收藏失败', 'status' => 0]);
//        }
    }
}
